package jane.mvc.utils;

import jane.mvc.engine.JaneClassloader;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.util.UUID;

import com.google.common.hash.Hashing;

public class Utils
{

	public Class getClassFromJarByName(String className, File jarfile)
	{

		URLClassLoader loader = (URLClassLoader) ClassLoader
				.getSystemClassLoader();
		JaneClassloader l = new JaneClassloader(loader.getURLs());
		try
		{
			l.addURL(jarfile.toURI().toURL());
		} catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Class c = null;
		try
		{
			c = l.loadClass(className);
		} catch (ClassNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return c;

	}

	public String jarEntryToJavaName(String jarentry)
	{

		if (jarentry.endsWith(".class"))
		{
			return jarentry.replace(".class", "").replace("/", ".");
		} else
		{
			return "";
		}

	}

	public String getClassBaseName(String fqn)
	{
		return fqn.substring(fqn.lastIndexOf('.') + 1);
	}

	public String getControllerIdentifier(String controllerClassName)
	{
		return controllerClassName.substring(0,
				controllerClassName.lastIndexOf("Controller"));
	}

	public String getDefaultViewFromControllerAndMethod(
			String controllerClassName, String methodName)
	{

		if (controllerClassName.lastIndexOf('.') > 0)
		{
			controllerClassName = getClassBaseName(controllerClassName);

		}

		String controllerIdentifier = getControllerIdentifier(controllerClassName);

		StringBuilder sb = new StringBuilder();

		sb.append("/Views/");
		sb.append(controllerIdentifier);
		sb.append("/");
		sb.append(methodName);
		sb.append(".jane");

		return sb.toString();

	}

	public String strToMD5(String str)
	{
		return Hashing.md5().hashBytes(str.getBytes(Charset.forName("UTF-8")))
				.toString();
	}

	public UUID getNewUUID()
	{
		return UUID.randomUUID();
	}

}
